package com.meitianhui.convenitenbuy.main.presenter;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.contract.LoginContract;
import com.meitianhui.convenitenbuy.main.http.MainApiDataSource;
import com.meitianhui.convenitenbuy.main.model.bean.AppToken;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.main.model.bean.PhoneCodeInfo;
import com.meitianhui.convenitenbuy.main.model.bean.StringResponse;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.main.model.bean.VerifyPhone;
import com.meitianhui.convenitenbuy.main.ui.LoginActivity;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerInfo;
import com.meitianhui.convenitenbuy.module.mine.model.UserAsset;
import com.meitianhui.convenitenbuy.module.mine.model.UserInfo;
import com.meitianhui.convenitenbuy.module.order.model.bean.EmptyInfo;
import com.meitianhui.convenitenbuy.push.PushUtils;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2017/10/28.
 */
public class LoginPresenter implements LoginContract.Presenter {

    private LoginActivity context;
    private final LoginContract.View view;

    @Inject
    public LoginPresenter(LoginContract.View view, LoginActivity context) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void getAppToken() {
        MainApiDataSource.getInstance()
                .getAppToken(Constants.APP_ID, Constants.PRIVATE_KEY)
                .subscribe(new ResponseObserver<BaseResponse<AppToken>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<AppToken> appToken) {
                        view.getAppTokenSuccess(appToken.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    /**
     * 验证会员
     */
    @Override
    public void verifyPhone(String phone) {
        MainApiDataSource.getInstance()
                .verifyPhone(InfoProvider.getAppToken(context), "consumer", phone)
                .subscribe(new ResponseObserver<BaseResponse<VerifyPhone>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<VerifyPhone> response) {
                        view.verifyPhoneSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getPhoneCodeMsg() {
        MainApiDataSource.getInstance()
                .getPhoneCodeMsg(InfoProvider.getAppToken(context), "infrastructure.securityVerify")
                .subscribe(new ResponseObserver<StringResponse>(context) {
                    @Override
                    public void onSuccess(StringResponse response) {
                        view.phoneCodeMsgSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getPhoneCode(String phone, String code, String imageCode) {
        MainApiDataSource.getInstance()
                .getPhoneCodeNew(InfoProvider.getAppToken(context), phone, code, imageCode)
                .subscribe(new ResponseObserver<BaseResponse<PhoneCodeInfo>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<PhoneCodeInfo> response) {
                        PhoneCodeInfo info = response.data;
                        String errorCode = info.getError_code();

                        if (!EmptyUtil.isEmpty(errorCode)) {
                            view.phoneCodeFailed(info.getError_msg());
                        } else {
                            view.phoneCodeSuccess("");
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void login(String phone, String code) {
        if (TextUtils.isEmpty(SystemUtils.getDeviceInfo(context))) {
            TipUtils.showToast(App.getInstance(), "未获取相关权限，请到权限管理中心设置");
        }

        MainApiDataSource.getInstance()
                .login(InfoProvider.getAppToken(context), SystemUtils.getDeviceModel(),
                        phone, "local_life", SystemUtils.getDeviceInfo(context), "consumer", code)
                .subscribe(new ResponseObserver<BaseResponse<UserToken>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<UserToken> response) {
                        view.loginSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.loginFail(msg);
                    }
                });
    }

    @Override
    public void getUserInfo() {
        MainApiDataSource.getInstance()
                .getUserInfo(InfoProvider.getUserToken(context).getUser_token())
                .subscribe(new ResponseObserver<BaseResponse<UserInfo>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<UserInfo> response) {
                        view.getUserInfoSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void getConsumerInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(context).getMember_id());
        String json = new Gson().toJson(map);

        MainApiDataSource.getInstance()
                .getConsumerInfo(InfoProvider.getAppToken(context), "member.consumerFind", json)
                .subscribe(new ResponseObserver<BaseResponse<ConsumerInfo>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<ConsumerInfo> response) {
                        view.getConsumerInfoSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }


    @Override
    public void getUserAsset() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(context).getMember_id());
        String json = new Gson().toJson(map);

        MainApiDataSource.getInstance()
                .getUserAsset(InfoProvider.getUserToken(context).getUser_token(),
                        "finance.memberAssetFind", json)
                .subscribe(new ResponseObserver<BaseResponse<UserAsset>>(context) {
                    @Override
                    public void onSuccess(BaseResponse<UserAsset> response) {
                        view.getUserAssetSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    /**
     * 获取环信的信息
     */
    @Override
    public void getHyphenateInfo(String nickName, String headPicPath) {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(context).getMember_id());
        map.put("member_type_key", "consumer");
        map.put("nickname", nickName);
        map.put("head_pic_path", headPicPath);
        String json = new Gson().toJson(map);

        MainApiDataSource.getInstance()
                .getHyphenateInfo(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        "chat.getIMUserLoginInfo", json)
                .subscribe(new ResponseObserver<BaseResponse<HyphenateInfo>>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseResponse<HyphenateInfo> response) {
                        view.getHyphenateSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void loginHyphenate(String imUserId) {
        EMClient.getInstance().login(imUserId, imUserId, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                view.onFail(code, message);
            }
        });
    }

    @Override
    public void postPushInfo() {
        UserToken token = InfoProvider.getUserToken(App.getInstance());
        String member_id = token.getMember_id();
        PushUtils.setAlias(context, member_id, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
            }
        });

        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("consumer");
        PushUtils.setTags(context, hashSet, null);
        String s_device = SystemUtils.getDeviceModel().replace(" ", "");
        String user_token = token.getUser_token();

        MainApiDataSource.getInstance()
                .postPushInfo(user_token, "consumer", "ANDROID", s_device, Constants.CUSTOM_APP, member_id)
                .subscribe(new ResponseObserver<BaseResponse<EmptyInfo>>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseResponse<EmptyInfo> versionInfoBaseResponse) {
                        view.postPushInfoSuccess();
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
